package com.liwenfeng.diancanspringboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.liwenfeng.diancanspringboot.common.constant.MessageConstant;
import com.liwenfeng.diancanspringboot.common.constant.StatusConstant;
import com.liwenfeng.diancanspringboot.common.context.BaseContext;
import com.liwenfeng.diancanspringboot.common.exception.OrderBusinessException;
import com.liwenfeng.diancanspringboot.common.exception.ShoppingCartBusinessException;
import com.liwenfeng.diancanspringboot.common.exception.UserNotLoginException;
import com.liwenfeng.diancanspringboot.common.result.PageResult;
import com.liwenfeng.diancanspringboot.mapper.*;
import com.liwenfeng.diancanspringboot.pojo.dto.*;
import com.liwenfeng.diancanspringboot.pojo.entity.*;
import com.liwenfeng.diancanspringboot.pojo.vo.OrderStatisticsVO;
import com.liwenfeng.diancanspringboot.pojo.vo.OrderSubmitVO;
import com.liwenfeng.diancanspringboot.pojo.vo.OrderVO;
import com.liwenfeng.diancanspringboot.service.OrderService;
import com.liwenfeng.diancanspringboot.service.ShoppingCartService;
import com.liwenfeng.diancanspringboot.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final ShoppingCartMapper shoppingCartMapper;
    private final WebSocketServer webSocketServer;
    private final EmployeeMapper employeeMapper;
    private final DishMapper dishMapper;
    private final SetmealMapper setmealMapper;
    private final TurnoverMapper turnoverMapper;

    public OrderServiceImpl(OrderMapper orderMapper, OrderDetailMapper orderDetailMapper, ShoppingCartMapper shoppingCartMapper, ShoppingCartService shoppingCartService, WebSocketServer webSocketServer, EmployeeMapper employeeMapper, DishMapper dishMapper, SetmealMapper setmealMapper, TurnoverMapper turnoverMapper) {
        this.orderMapper = orderMapper;
        this.orderDetailMapper = orderDetailMapper;
        this.shoppingCartMapper = shoppingCartMapper;
        this.webSocketServer = webSocketServer;
        this.employeeMapper = employeeMapper;
        this.dishMapper = dishMapper;
        this.setmealMapper = setmealMapper;
        this.turnoverMapper = turnoverMapper;
    }

    // 用户下单（手机端user模块)
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 判断当前用户的购物车中是否有被下架的菜品或套餐
        HashSet<String> disableNames = new HashSet<>();
        List<ShoppingCartDTO> dishList = ordersSubmitDTO.getShoppingCartList().stream().filter(item -> item.getDishId() != null).toList();
        List<ShoppingCartDTO> setmealList = ordersSubmitDTO.getShoppingCartList().stream().filter(item -> item.getSetmealId() != null).toList();
        if (dishList.size()>0) {
            Dish dish = new Dish();
            dish.setStatus(StatusConstant.DISABLE);
            List<Long> disableDishes = dishMapper.list(dish).stream().map(Dish::getId).toList();
            List<ShoppingCartDTO> disableDishList = dishList.stream().filter(item -> disableDishes.contains(item.getDishId())).toList();
            if (disableDishList.size()>0){
                disableDishList.forEach(item -> {
                    disableNames.add(item.getName());
                });
            }
        }
        if (setmealList.size()>0) {
            Setmeal setmeal = new Setmeal();
            setmeal.setStatus(StatusConstant.DISABLE);
            List<Long> disableSetmeals = setmealMapper.list(setmeal).stream().map(Setmeal::getId).toList();
            List<ShoppingCartDTO> disableSetmealList = setmealList.stream().filter(item -> disableSetmeals.contains(item.getSetmealId())).toList();
            if (disableSetmealList.size()>0){
                disableSetmealList.forEach(item -> {
                    disableNames.add(item.getName());
                });
            }
        }
        // 如果有，拼接成字符串，并返回给前端
        if (disableNames.size()>0){
            StringBuilder sb = new StringBuilder();
            for (String name : disableNames) {
                sb.append(name).append("、");
            }
            String s = sb.substring(0, sb.length() - 1);
            OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
            orderSubmitVO.setSellOutList(s);
            return orderSubmitVO;
        }

        Long userId = BaseContext.getCurrentId();

        // 向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        String autoAccept = getAutoAccept();
        if (autoAccept.equals("1")) {
            orders.setStatus(Orders.CONFIRMED);
        } else {
            orders.setStatus(Orders.TO_BE_CONFIRMED);
        }

        orderMapper.insert(orders);

        // 向订单明细表插入n条数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        Turnover turnover = turnoverMapper.getById(ordersSubmitDTO.getTurnoverId());

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setTurnoverId(turnover.getId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null) {
            throw new ShoppingCartBusinessException("购物车为空,请先添加菜品或套餐到购物车");
        }
        ordersSubmitDTO.getShoppingCartList().forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            List<ShoppingCart> shoppingCarts = shoppingCartList.stream().filter(item1 -> {
                return Objects.equals(item1.getDishId(), item.getDishId()) && Objects.equals(item1.getSetmealId(), item.getSetmealId()) && Objects.equals(item1.getDishFlavor(), item.getDishFlavor());
            }).toList();
            if (shoppingCarts.size() == 0) {
                throw new ShoppingCartBusinessException("购物车中没有你要添加的选项,请先添加菜品或套餐到购物车");
            }
//            if (item.getNumber() > shoppingCarts.get(0).getNumber()) {
//                throw new ShoppingCartBusinessException("下单数量与购物车内数量不符,请确认已下单数量后重新下单");
//            }
            if (item.getNumber() < shoppingCarts.get(0).getNumber()) {
                shoppingCartMapper.updateNumberById(shoppingCarts.get(0).getNumber() - item.getNumber(), shoppingCarts.get(0).getId());
            } else {
                shoppingCartMapper.deleteById(shoppingCarts.get(0).getId());
            }
            orderDetail.setName(shoppingCarts.get(0).getName());
            orderDetail.setImage(shoppingCarts.get(0).getImage());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setOrderId(orders.getId());
            orderDetail.setPlace(turnover.getPlace());
            orderDetail.setCompleteTime(LocalDateTime.now());

            if (Category.CATEGORY_NAME_WHITE.contains(item.getCategoryName())) {
                orderDetail.setStatus(OrderDetail.TO_BE_SEND);
                orderDetail.setNumber(item.getNumber());
                orderDetails.add(orderDetail);
            } else {
                orderDetail.setStatus(OrderDetail.TO_BE_DOING);
                orderDetail.setNumber(1);
                for (int i = 0; i < item.getNumber(); i++) {
                    orderDetails.add(orderDetail);
                }
            }
        });

        orderDetailMapper.insertBatch(orderDetails);
        // 校验：如果订单金额和数据库中的金额不一致，更新订单金额
        if (orders.getAmount().doubleValue() != getAmountByOrderId(orders.getId())) {
            Orders orders1 = new Orders();
            orders1.setId(orders.getId());
            orders1.setAmount(BigDecimal.valueOf(getAmountByOrderId(orders.getId())));
            orderMapper.update(orders1);
        }
        // 以下代码需要删除 todo

        // 暂时模拟一下订单号---------------------------------------------------

        Map map = new HashMap();
        map.put("type", 1);//1来单提醒，2客户催单
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());

        String json = JSON.toJSONString(map);
        //向客户端推送消息
        webSocketServer.sendToAllClient(json);

        // 模拟代码结束---------------------------------------------------

        // 封装VO并返回-微信支付需要的参数
//        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
//        orderSubmitVO.setId(orders.getId());
//        orderSubmitVO.setOrderNumber(orders.getNumber());
//        orderSubmitVO.setOrderAmount(orders.getAmount());
//        orderSubmitVO.setOrderTime(orders.getOrderTime());
//        return orderSubmitVO;
        return null;
    }

    /**
     * 用户端订单分页查询
     */
//    @Override
//    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
//        // 设置分页
//        PageHelper.startPage(pageNum, pageSize);
//
//        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
//        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
//        ordersPageQueryDTO.setStatus(status);
//
//        // 分页条件查询
//        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
//
//        List<OrderVO> list = new ArrayList<>();
//
//        // 查询出订单明细，并封装入OrderVO进行响应
//        if (page != null && page.getTotal() > 0) {
//            for (Orders orders : page) {
//                Long orderId = orders.getId();// 订单id
//
//                // 查询订单明细
//                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
//
//                OrderVO orderVO = new OrderVO();
//                BeanUtils.copyProperties(orders, orderVO);
//                orderVO.setOrderDetailList(orderDetails);
//
//                list.add(orderVO);
//            }
//        }
//        return new PageResult(page.getTotal(), list);
//    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 用户取消订单 todo 不需要，用户只能取消详情菜品
     */
//    @Override
//    public void userCancelById(Long id) throws Exception {
//        // 根据id查询订单
//        Orders ordersDB = orderMapper.getById(id);
//
//
//        // 校验订单是否存在
//        if (ordersDB == null) {
//            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
//        }
//
//        //1.待接单，2.未完成，3.已完成，4.已取消
//        if (ordersDB.getStatus() > 2) {
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//        List<OrderDetail> orderDetailList = orderDetailMapper.getValidByOrderId(id);
//        if (orderDetailList == null || orderDetailList.size() == 0) {
//            Orders orders = new Orders();
//            orders.setId(id);
//            orders.setStatus(Orders.CANCELLED);
//            orderMapper.update(orders);
//            throw new OrderBusinessException("订单无需取消");
//        }
//
//        orderDetailList.forEach(item -> {
//            if (item.getStatus() > 0 && item.getStatus() != 4) {
//                throw new OrderBusinessException("订单中有正在加工的菜品，不能取消");
//            }
//        });
//
//        OrdersCancelDTO ordersCancelDTO = new OrdersCancelDTO();
//        ordersCancelDTO.setId(id);
//        ordersCancelDTO.setCancelReason("客户取消");
//        cancel(ordersCancelDTO);
//    }
//
//    /**
//     * 再来一单
//     */
//    @Override
//    public void repetition(Long id) {
//        // 查询当前用户id
//        Long userId = BaseContext.getCurrentId();
//
//        // 根据订单id查询当前订单详情
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
//
//        // 将订单详情对象转换为购物车对象
//        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
//            ShoppingCart shoppingCart = new ShoppingCart();
//
//            // 将原订单详情里面的菜品信息重新复制到购物车对象中
//            BeanUtils.copyProperties(x, shoppingCart, "id");
//            shoppingCart.setUserId(userId);
//            // todo 设置桌号
//            shoppingCart.setCreateTime(LocalDateTime.now());
//
//            return shoppingCart;
//        }).collect(Collectors.toList());
//
//        // 将购物车对象批量添加到数据库
//        shoppingCartMapper.insertBatch(shoppingCartList);
//    }

    /**
     * 订单搜索
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        for (OrderVO orderVO : page.getResult()) {
            orderVO.setOrderDishes(getOrderDishesStr(orderVO));
        }

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据订单id获取菜品信息字符串
     */
    private String getOrderDishesStr(OrderVO orderVO) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderVO.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、未完成的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        return orderStatisticsVO;
    }

    /**
     * 接单
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orderDB = orderMapper.getById(ordersConfirmDTO.getId());
        if (orderDB == null || !Objects.equals(orderDB.getStatus(), Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);

        orderMapper.update(orders);
    }

    /**
     * 拒单 todo 用取消订单代替
     */
//    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
//        // 根据id查询订单
//        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
//
//        // 订单只有存在且状态为1（待接单）才可以拒单
//        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//        //支付状态
////        Integer payStatus = ordersDB.getPayStatus();
////        if (payStatus == Orders.PAID) {
////            //用户已支付，需要退款
////            String refund = weChatPayUtil.refund(
////                    ordersDB.getNumber(),
////                    ordersDB.getNumber(),
////                    new BigDecimal(0.01),
////                    new BigDecimal(0.01));
////            log.info("申请退款：{}", refund);
////        }
//
//        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
//        Orders orders = new Orders();
//        orders.setId(ordersDB.getId());
//        orders.setStatus(Orders.CANCELLED);
//        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
//        orders.setCancelTime(LocalDateTime.now());
//
//        orderMapper.update(orders);
//    }

    /**
     * 取消订单
     */
    @Override
    @Transactional
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        if (ordersDB == null || Objects.equals(ordersDB.getStatus(), Orders.CANCELLED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 管理端取消订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setAmount(BigDecimal.valueOf(0));
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(ordersCancelDTO.getId());
        orderDetail.setStatus(OrderDetail.CANCELLED);
        orderDetailMapper.update(orderDetail);
    }

//    /**
//     * 派送订单 todo 改成服务员上菜
//     */
//    public void delivery(Long id) {
//        // 根据id查询订单
//        Orders ordersDB = orderMapper.getById(id);
//
//        // 校验订单是否存在，并且状态为3
//        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//        Orders orders = new Orders();
//        orders.setId(ordersDB.getId());
//        // 更新订单状态,状态转为派送中
//        orders.setStatus(Orders.COMPLETED);
//
//        orderMapper.update(orders);
//    }

    /**
     * 改订单状态为已完成(浏览器端点击完成)
     */
    @Override
    @Transactional
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setStatus(OrderDetail.COMPLETED);
        orderDetail.setOrderId(id);
        orderDetailMapper.update(orderDetail);

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        double amountByOrderId = getAmountByOrderId(orders.getId());
        if (amountByOrderId == 0) {
            orders.setAmount(BigDecimal.valueOf(0));
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
        } else {
            orders.setAmount(BigDecimal.valueOf(amountByOrderId));
            orders.setStatus(Orders.COMPLETED);
            orders.setCompleteTime(LocalDateTime.now());
        }
        // 更新订单状态,状态转为完成

        orderMapper.update(orders);

    }

    /**
     * 客户催单
     */
    @Override
    public void reminder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type", 2); //1表示来单提醒 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + ordersDB.getNumber());

        //通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 获取自动接单设置
     */
    @Override
    public String getAutoAccept() {
        Employee byId = employeeMapper.getById(1L);
        return byId.getSex();
    }

    /**
     * 设置自动接单
     */
    @Override
    public void setAutoAccept(String auto) {
        Employee employee = new Employee();
        employee.setId(1L);
        employee.setSex(auto);
        employeeMapper.update(employee);
    }

    /**
     * 更新订单菜品数量
     */
//    @Override
//    @Transactional
//    public void updateDishUpdate(OrderUpdateDTO orderUpdateDTO) {
//        OrderDetail orderDetail = new OrderDetail();
//        orderDetail.setId(orderUpdateDTO.getDetailId());
//        orderDetail.setStatus(orderUpdateDTO.getDetailStatus());
//        orderDetail.setNumber(orderUpdateDTO.getDetailNum());
//        orderDetailMapper.update(orderDetail);
//
//        Orders orders = new Orders();
//        orders.setId(orderUpdateDTO.getOrderId());
//        double amountByOrderId = getAmountByOrderId(orderUpdateDTO.getOrderId());
//        if (amountByOrderId != 0) {
//            orders.setAmount(BigDecimal.valueOf(amountByOrderId));
//        } else {
//            orders.setAmount(BigDecimal.valueOf(0));
//            orders.setStatus(Orders.CANCELLED);
//        }
//        orderMapper.update(orders);
//
//    }

    // 按流水号查询订单列表，包含详情（手机端user模块）(浏览器端）
    @Override
    public List<OrderVO> getOrderListByTurnoverId(Long turnoverId) {
        List<Orders> ordersList = orderMapper.getUnpayByTurnoverId(turnoverId);
        if (ordersList != null && ordersList.size() > 0) {
            return ordersList.stream().map(item -> {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(item, orderVO);
                orderVO.setOrderDetailList(orderDetailMapper.getValidByOrderId(item.getId()));
                return orderVO;
            }).collect(Collectors.toList());
        }
        return List.of();
    }

    /**
     * 添加订单
     */
    @Transactional
    public void addOrder(OrdersDTO ordersDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.CONFIRMED);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orderMapper.insert(orders);

        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        ordersDTO.getOrderDetails().forEach(item -> {
            for (int i = 0; i < item.getNumber(); i++) {
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(item, orderDetail);
                orderDetail.setOrderId(orders.getId());
                orderDetail.setStatus(Category.CATEGORY_NAME_WHITE.contains(ordersDTO.getCategoryName()) ? 2 : 0);
                orderDetail.setNumber(1);
                orderDetail.setPlace(ordersDTO.getPlace());
                orderDetails.add(orderDetail);
            }
        });
        orderDetailMapper.insertBatch(orderDetails);
    }

    // 根据桌号查询订单详情（暂用，以后按桌号查订单，用订单id查详情）
//    @Override
//    public List<OrderDetail> getOrderDetailByPlace(Integer place) {
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByPlace(place);
//        return orderDetailList;
//    }

    // 用户取消一件待加工菜品(手机端user模块)
    @Override
    public void cancelOrderDetail(OrderDetailCancelDTO orderDetailCancelDTO) {
        if (BaseContext.getOther()==null){
            throw new UserNotLoginException("参数错误，请重新登录");
        }
        orderDetailCancelDTO.setTurnoverId(Long.valueOf(BaseContext.getOther()));
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetails(orderDetailCancelDTO);
        if (orderDetails == null || orderDetails.size() == 0) {
            throw new OrderBusinessException("订单状态错误，请刷新后重新操作");
        }
        OrderDetail orderDetail1 = orderDetails.get(0);
        OrderDetail orderDetail2 = new OrderDetail();
        orderDetail2.setId(orderDetail1.getId());
        if (orderDetail1.getNumber() > orderDetailCancelDTO.getNumber()) {
            orderDetail2.setNumber(orderDetail1.getNumber() - orderDetailCancelDTO.getNumber());
        } else {
            orderDetail2.setStatus(OrderDetail.CANCELLED);
        }
        orderDetailMapper.update(orderDetail2);

        List<OrderDetail> validByOrderId = orderDetailMapper.getValidByOrderId(orderDetail1.getOrderId());
        Orders orders = new Orders();
        orders.setId(orderDetail1.getOrderId());
        if (validByOrderId.size() == 0) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("用户取消");
            orders.setAmount(BigDecimal.valueOf(0));
            orderMapper.update(orders);
            return;
        }
        List<OrderDetail> toList = validByOrderId.stream().filter(item -> item.getStatus() != 3).toList();
        double sum = validByOrderId.stream().mapToDouble(item -> item.getAmount().doubleValue() * item.getNumber()).sum();
        orders.setAmount(BigDecimal.valueOf(sum));
        if (toList.size() == 0) {
            orders.setStatus(Orders.COMPLETED);
            orders.setCompleteTime(LocalDateTime.now());
        }
        orderMapper.update(orders);
    }

    // 按状态查询订单列表  todo 改造 应该没用 待确认
    @Override
    public List<OrderVO> listByStatus(Integer status) {
        String job = BaseContext.getOther();
        if (job == null)
            throw new UserNotLoginException("参数错误，请重新登录");
        List<Integer> orderDetailStatusList = new ArrayList<>();
        if (job.equals("厨师")) {
            orderDetailStatusList.add(OrderDetail.TO_BE_DOING);
            orderDetailStatusList.add(OrderDetail.DOING);
        } else if (job.equals("服务员")) {
            orderDetailStatusList.add(OrderDetail.TO_BE_SEND);
        } else if (List.of("0", "1").contains(job)) {
            orderDetailStatusList.add(OrderDetail.TO_BE_DOING);
            orderDetailStatusList.add(OrderDetail.DOING);
            orderDetailStatusList.add(OrderDetail.TO_BE_SEND);
        }
        if (orderDetailStatusList.size() == 0)
            return null;
        List<OrderDetail> orderDetails = orderDetailMapper.listByStatus(orderDetailStatusList);
        if (orderDetails == null)
            return null;
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(status, LocalDateTime.now());
        if (ordersList == null || ordersList.size() == 0)
            return null;
        return ordersList.stream().map(item -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(item, orderVO);
            orderVO.setOrderDetailList(orderDetails.stream().filter(orderDetail -> orderDetail.getOrderId().equals(item.getId())).toList());
            return orderVO;
        }).collect(Collectors.toList());
    }

    private double getAmountByOrderId(Long id) {
        List<OrderDetail> orderDetailList = orderDetailMapper.getValidByOrderId(id);
        return orderDetailList.stream().mapToDouble(item -> item.getAmount().doubleValue() * item.getNumber()).sum();
    }
}
